Imports System.Drawing.Printing
Public Class Form1
    Dim pageset As Printing.PageSettings = New Printing.PageSettings()
    ''' <summary>载入窗体</summary>
    ''' <param name="sender">触发对象</param>
    ''' <param name="e">对象事件基类</param>
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        ControlLocation()

        For Each foundFile As String In My.Computer.FileSystem.GetFiles(Application.StartupPath, FileIO.SearchOption.SearchAllSubDirectories, "*.mmt")
            ListBox1.Items.Add(foundFile) '从当前程序目录下搜索所有子目录的MMT项目文件添加到列表
        Next

    End Sub
    ''' <summary>循环检索列表显示的所有文件</summary>
    Private Sub RetrievalFiles()

        Dim link As String = Chr(9) '
        Dim lng As Integer = ListBox1.Items.Count - 1 '列表数

        Dim outstr As String = ""
        For i As Integer = 0 To lng
            Application.DoEvents()
            ListBox1.SetSelected(i, True) '选择列表项
            Dim TMPstr As String = ListBox1.Items(i) '取得列表项字符

            ReplaceLowOrderASCIICharacters(TMPstr)

            RetrievalFile(TMPstr, outstr, CheckBox1.Checked)
            TextBox1.Text = TextBox1.Text & "---------------------------------------------------------------------------------------------------------------------------" & vbCrLf
            TextBox1.Text = TextBox1.Text & "测量人" & link & "设备号" & link & "测站编码" & link & "测站名" & link & "测验日期" & link & "风力" & link & "风向" & link & "测次" & link & "备注" & link & "开始水位" & link & "结束水位" & vbCrLf
            TextBox1.Text = TextBox1.Text & outstr
        Next
    End Sub
    ''' <summary>调整窗体大小</summary>
    ''' <param name="sender">触发对象</param>
    ''' <param name="e">对象事件基类</param>
    Private Sub Form1_Resize(sender As Object, e As EventArgs) Handles Me.Resize
        ControlLocation()
    End Sub
    ''' <summary>数据检索按钮</summary>
    ''' <param name="sender">触发对象</param>
    ''' <param name="e">对象事件基类</param>
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        TextBox1.Text = ""
        RetrievalFiles()
    End Sub
    ''' <summary>调整控件位置</summary>
    Private Sub ControlLocation()
        ListBox1.Width = Me.ClientSize.Width * 0.32
        TextBox1.Width = Me.ClientSize.Width * 0.62
        Button1.Left = ListBox1.Width + Me.ClientSize.Width * 0.06 / 2 - Button1.Width / 2
        Button2.Left = Button1.Left
        Button3.Left = Button1.Left
        btnPageSetup.Left = Button1.Left
        btnPrintPreview.Left = Button1.Left
        CheckBox1.Left = ListBox1.Width + Me.ClientSize.Width * 0.06 / 2 - CheckBox1.Width / 2
        With pageset.Margins
            .Top = 15
            .Bottom = 15
            .Left = 15
            .Right = 15
        End With
        PrintDocument1.DefaultPageSettings.Margins = pageset.Margins
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Clipboard.SetDataObject(TextBox1.Text, False)
    End Sub


    ''' <summary>
    ''' PrintPage 是打印事件。对于要打印的每一页都会激发此事件。也可以处理 BeginPrint 和EndPrint 事件以获得更多的控制。
    ''' 下面的代码对纯文本的执行速度很快且很有用，因为 MeasureString 计算可以适合整页的文本。但是，对于 
    ''' 格式化文本则不那么有用。如果是格式化文本，则需要具有更加复杂的字级别（相对于页级别）控件。
    ''' </summary>
    Private Sub pdoc_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        ' 声明一个变量来保存最后一个打印字符的位置。声明为静态以便后面的 PrintPage 事件可以引用该变量。
        Static intCurrentChar As Int32
        ' 初始化要用于打印的字体。
        Dim font As New Font("宋体", 8, FontStyle.Regular)

        Dim intPrintAreaHeight, intPrintAreaWidth, marginLeft, marginTop As Int32
        PrintDocument1.DefaultPageSettings = pageset

        With PrintDocument1.DefaultPageSettings

            ' 初始化包含打印区域矩形的边界的局部变量。

            intPrintAreaHeight = .PaperSize.Height - .Margins.Top - .Margins.Bottom
            intPrintAreaWidth = .PaperSize.Width - .Margins.Left - .Margins.Right

            ' 初始化局部变量以保存将用作打印区域矩形左上角的 X 和 Y 坐标的边距值。
            marginLeft = .Margins.Left ' X 坐标
            marginTop = .Margins.Top ' Y 坐标
        End With

        ' 如果用户选择了“横向”模式，则交换打印区域的高度与宽度。
        If PrintDocument1.DefaultPageSettings.Landscape Then
            Dim intTemp As Int32
            intTemp = intPrintAreaHeight
            intPrintAreaHeight = intPrintAreaWidth
            intPrintAreaWidth = intTemp
        End If

        ' 根据打印区域的高度和字体的高度计算文档中的总行数。
        Dim intLineCount As Int32 = CInt(intPrintAreaHeight / font.Height)
        ' 初始化定义打印区域的矩形结构。
        Dim rectPrintingArea As New RectangleF(marginLeft, marginTop, intPrintAreaWidth, intPrintAreaHeight)

        ' 将 StringFormat 类实例化，该类封装文本布局信息（如对齐方式和行距），显示操作(如省略号插入和区域数字替换）和 OpenType 功能。使用 StringFormat 可使
        ' MeasureString 和 DrawString 在打印每页时仅使用整数行而忽略非完整行。如果每页的打印区域高度不能整除每页的行数（通常都会如此），
        ' 非完整行在其他情况下可能会打印。请参见 SDK 文档中有关 StringFormatFlags 的进一步讨论。
        Dim fmt As New StringFormat(StringFormatFlags.MeasureTrailingSpaces + StringFormatFlags.NoWrap + StringFormatFlags.LineLimit + StringFormatFlags.FitBlackBox)
        ' 调用 MeasureString 确定适合打印区域矩形的字符数。向 CharFitted Int32 传递 ByRef，并在稍后用于
        ' 计算 intCurrentChar，进而计算 HasMorePages。LinesFilled 对于本示例不是必要的，但必须在传递 CharsFitted 时进行传递。
        ' Mid 用于传递从打印的上一页断开的剩余文本段（回想一下，intCurrentChar 是声明为静态的）。
        Dim intLinesFilled, intCharsFitted As Int32
        e.Graphics.MeasureString(Mid(TextBox1.Text, intCurrentChar + 1), font, New SizeF(intPrintAreaWidth, intPrintAreaHeight), fmt, intCharsFitted, intLinesFilled)

        ' 将文本打印到页。
        e.Graphics.DrawString(Mid(TextBox1.Text, intCurrentChar + 1), font, Brushes.Black, rectPrintingArea) ', fmt)

        ' 使当前字符前进到在此页上打印的最后一个字符。因为 
        ' intCurrentChar 是静态变量，所以它的值可以用于
        ' 要打印的下一页。使它前进 1 个字符并将其传递到 Mid()
        ' 以打印下一页（请参见上面 MeasureString()）。
        intCurrentChar += intCharsFitted

        ' HasMorePages 通知打印模块是否应激发
        ' 另一个 PrintPage 事件。
        If intCurrentChar < TextBox1.Text.Length Then
            e.HasMorePages = True
        Else
            e.HasMorePages = False
            ' 因为 intCurrentChar 是静态的，所以必须显式重置它。
            intCurrentChar = 0
        End If
    End Sub
    ''' <summary>
    ''' 在呈现预览时，PrintPreviewDialog 与 PrintDocument 相关联,
    ''' 并触发 PrintPage 事件。向 PrintPage 事件传递
    ''' 一个在其中“绘制”页的图形上下文。
    ''' </summary>
    Private Sub btnPrintPreview_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrintPreview.Click
        Try
            Dim PrintPreviewDialog1 As New PrintPreviewDialog
            PrintPreviewDialog1.Height = My.Computer.Screen.Bounds.Height
            PrintPreviewDialog1.Width = My.Computer.Screen.Bounds.Width
            PrintPreviewDialog1.MaximizeBox = False
            PrintPreviewDialog1.MinimizeBox = False
            PrintPreviewDialog1.PrintPreviewControl.Zoom = 1.0
            PrintPreviewDialog1.WindowState = FormWindowState.Maximized
            PrintDocument1.DocumentName = "ADCP测流原始数据"
            PrintPreviewDialog1.Document = PrintDocument1
            '  AddHandler PrintDocument1.PrintPage, AddressOf pdoc_PrintPage
            PrintPreviewDialog1.ShowDialog()
        Catch exp As Exception
            MsgBox("在尝试打印预览时加载文档时发生错误。确保您当前可以访问打印机。打印机必须已连接且可访问，才能进行打印预览。", MsgBoxStyle.OkOnly, Me.Text)
        End Try
    End Sub

    ''' <summary>
    ''' 使用页面设置可以指定纸张大小、纵向、 横向等内容。
    ''' </summary>
    Private Sub btnPageSetup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPageSetup.Click

        With PageSetupDialog1
            '   PrintDocument1.DocumentName = "ADCP测流原始数据"
            .Document = PrintDocument1
            .AllowMargins = True
            .PageSettings = PrintDocument1.DefaultPageSettings
        End With

        If PageSetupDialog1.ShowDialog() = DialogResult.OK AndAlso System.Globalization.RegionInfo.CurrentRegion.IsMetric AndAlso Environment.OSVersion.Platform <> PlatformID.Unix Then
            PageSetupDialog1.PageSettings.Margins = PrinterUnitConvert.Convert(PageSetupDialog1.PageSettings.Margins, PrinterUnit.Display, PrinterUnit.TenthsOfAMillimeter) '默认英尺转公尺
            pageset = PageSetupDialog1.PageSettings
        End If

    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim printdialog1 As New PrintDialog()
        '   PrintDocument1.DocumentName = "ADCP测流原始数据"
        printdialog1.Document = PrintDocument1
        '  AddHandler PrintDocument1.PrintPage, AddressOf pdoc_PrintPage
        If printdialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            PrintDocument1.Print()
        End If
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs)
        Try
            Dim PDoc As New PrintDocument
            PDoc.DocumentName = "ADCP测流原始数据"
            PDoc.DefaultPageSettings.Landscape = False '纵向

            AddHandler PDoc.PrintPage, AddressOf Me.PText

            Dim printdialog1 As New PrintDialog()
            printdialog1.Document = PDoc
            printdialog1.AllowCurrentPage = True

            Dim rusult As DialogResult = printdialog1.ShowDialog()
            If rusult = DialogResult.OK Then
                PDoc.Print()

            End If
        Catch ex As Exception
            MessageBox.Show("错误", ex.ToString)
        End Try
    End Sub


    Private Sub PText(ByVal sender As Object, ByVal e As PrintPageEventArgs)

        e.Graphics.DrawString(TextBox1.Text, New Font("宋体", 8, FontStyle.Regular), Brushes.Black, 20, 20)

        e.HasMorePages = False
    End Sub


End Class
